package com.ay.shardingshere.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;

/**
 * @Author: ay
 * @Date: 2021/6/29
 * @Description:
 **/
@Slf4j
public class DatabaseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {

        System.out.println("DB  PreciseShardingAlgorithm  ");
        // 真实节点
        collection.stream().forEach((item) -> {
            log.info("actual node db:{}", item);
        });

        log.info("logic table name:{},rout column:{}", preciseShardingValue.getLogicTableName(), preciseShardingValue.getColumnName());

        //精确分片
        log.info("column value:{}", preciseShardingValue.getValue());

        String db_name = "ds";

        // 根据当前日期 来 分库分表
        Date date = preciseShardingValue.getValue();
        String year = String.format("%tY", date);
        String month = String.format("%tm", date);
        String day = String.format("%td", date);

        for (String each : collection) {
            if (each.equals(db_name + year)) {
                return each;
            }
        }
        throw new IllegalArgumentException();
    }
}
